package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1.检查phone格式
        if (!RegexUtils.isCodeInvalid(phone)) {
            return Result.fail("电话号码格式错误！");
        }
        // 2.发送验证码
        String code = RandomUtil.randomNumbers(6);
        // 3.保存在redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.info("验证码已存入Redis，key: {}, code: {}", LOGIN_CODE_KEY + phone,code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1.检查phone格式
        String phone = loginForm.getPhone();
        if (!RegexUtils.isCodeInvalid(phone)) {
            return Result.fail("电话号码格式错误！");
        }
        // 2.验证码比对
        String code = loginForm.getCode();
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (cacheCode == null){
            return Result.fail("验证码不存在!");
        }
        if (!code.equals(cacheCode)){
            return Result.fail("验证码错误！");
        }
        // 3.账号密码比对
        User user = query().eq("phone",phone).one();
        if (user == null){
            // TODO 不合理 4.不存在则创建新用户
            user = createUserWithPhone(phone);
        }
        // redis 改写
        // 生成token, 作为登录令牌
        String token = UUID.randomUUID().toString();
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        // 保存用户信息 (Hash储存)
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY  + token, BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())));
        // 设置有效期 存在问题 有效期不会因为用户访问更新
        stringRedisTemplate.expire(LOGIN_USER_KEY  + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
        // 返回token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        UserDTO user = UserHolder.getUser();
        if (user == null)
            return Result.ok("没有用户信息！");
        // 1. 获取登录用户
        Long userId = user.getId();
        // 2. 获取日期
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 3. redis key
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 4. redis value
        stringRedisTemplate.opsForValue().setBit(key,now.getDayOfMonth() - 1,true);
        return Result.ok("签到成功！");
    }

    @Override
    public Result signCount() {
        UserDTO user = UserHolder.getUser();
        if (user == null)
            return Result.ok("没有用户信息！");
        // 获取连续的签到次数
        // 1. 访问redis获取签到的天数数据 (本月)
        String key = USER_SIGN_KEY + user.getId() + LocalDateTime.now().format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int day = LocalDateTime.now().getDayOfMonth();
        // BITFIELD sign:userId:time GET u14 0;
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                // 子命令
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0)
        );
        if (result == null || result.isEmpty()){
            return Result.ok(0);
        }
        Long num = result.get(0);
        // 2. 统计
        int count = 0;
        while(true){
            if ((num & 1) == 0) {
                break;
            }else {
                count++;
            }
            num >>>= 1;
        }
        // 3. 返回
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        // 保存到数据库
        save(user);
        return user;
    }
}
